package cn.jee;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipDir {
  public static void main(String[] args)throws Exception {
    if(args.length==0){
      System.out.println("请指定目录");
      return;
    }
    System.out.println(args[0]);
    ZipDir zipDir=new ZipDir(args[0]);
    zipDir.closeDb();
    zipDir.init();
  }

  File rootFile;
  Path startDir;
  ZipOutputStream zipOutputStream;
  String[] includeDirs={".git","src","logs"};
  public ZipDir(String root) throws FileNotFoundException {
    this.rootFile = new File(root);
    this.startDir=rootFile.getParentFile().toPath();
    String destZipName=rootFile.getName().replace(".", "")+".zip";
    File destZipFile=new File(rootFile.getParentFile(), destZipName);
    zipOutputStream=new ZipOutputStream(new FileOutputStream(destZipFile));
  }
  public void closeDb() throws ClassNotFoundException {
    String driver = "org.hsqldb.jdbc.JDBCDriver";
    String url = "jdbc:hsqldb:hsql://localhost";
    String user="sa";
    String pass="";
    Class.forName(driver);
    try(Connection con= DriverManager.getConnection(url,user,pass);
        Statement st=con.createStatement();){
      st.executeUpdate("shutdown");
    }catch(Exception e){
      //不处理
    }
  }
  public void init() throws IOException {
    putNewZipEntry(rootFile);
    for(String dir:includeDirs){
      File dirFile=new File(rootFile,dir);
      zip(dirFile);
    }
    zip(new File(rootFile,"db/test.script"));
    for(File file:rootFile.listFiles()){
      if(file.isFile()) zip(file);
    }
    zipOutputStream.close();
  }
  public void zip(File dir) throws IOException {
    putNewZipEntry(dir);
    if(dir.isDirectory()){
      for(File file:dir.listFiles()){
        zip(file);
      }
    }else{
      zipOutputStream.write(Files.readAllBytes(dir.toPath()));
    }
  }
  private void putNewZipEntry(File file) throws IOException {
    String zipEntryName=startDir.relativize(file.toPath()).toString();
    if(file.isDirectory()) {
      zipEntryName+="/";
    }
    zipOutputStream.putNextEntry(new ZipEntry(zipEntryName));
  }
}
